<template>
  <div class="sign-page">
    <div class="signup">
      <div class="header">
        <h2 class="title">欢迎注册</h2>
        <router-link to="/login" class="link">已有账号，去登录 &gt;</router-link>
      </div>
      <div class="body">
        <!-- 账号注册 -->
        <el-form class="v-form" :model="signForm" ref="signForm" :rules="signFormRules">
          <el-form-item class="v-form-item pre-icon" prop="mobile">
            <i class="icon-mobile"></i>
            <el-input v-model="signForm.mobile" size="medium" placeholder="请输入手机号码" maxlength="11" clearable></el-input>
          </el-form-item>
          <el-form-item class="v-form-item" prop="imgCode">
            <el-input v-model="signForm.imgCode" size="medium" placeholder="请输入图片验证码" maxlength="4" @blur="checkImgCode" @change="isImgCodeRight = false" clearable>
              <template slot="append">
                <img :src="imgCodeSrc" class="image-code" @click="getImgCode">
              </template>
            </el-input>
            <p class="v-valid-tips success" v-show="isImgCodeRight">验证码输入正确</p>
          </el-form-item>
          <el-form-item class="v-form-item" prop="msgCode">
            <el-input v-model="signForm.msgCode" size="medium" placeholder="请输入短信验证码" maxlength="6" clearable>
              <template slot="append">
                <button type="button" class="inner-btn" :class="{'disabled': sendMsg}" :disabled="sendMsg" @click="sendMsgCode">{{msgTip}}</button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item class="v-form-item pre-icon " prop="password">
            <i class="icon-lock"></i>
            <el-input v-model="signForm.password" size="medium" type="password" placeholder="请输入密码" maxlength="20" clearable></el-input>
          </el-form-item>
        </el-form>
        <!-- 登录按钮 -->
        <div class="sign-btn" @click="signup">注册</div>
        <div class="bottom">
          <el-checkbox v-model="isAgreed"><p style="font-size: 12px">我已阅读并同意好茶仓的＜用户协议＞</p></el-checkbox>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Md5 from 'js-md5'
export default {
  data () {
    return {
      signForm: {
        operateType: 'regist',
        mobile: '',
        imgCode: '',
        msgCode: '',
        password: ''
      },
      signFormRules: {
        mobile: [
          {required: true, message: '请输入手机号码', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (value.trim() === '') {
                callback(new Error('请输入手机号码'))
              } else if (!(/^1[3456789]\d{9}$/.test(value))) {
                callback(new Error('您输入手机号码不正确'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        imgCode: [
          {required: true, message: '请输入图片验证码', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (!/^[a-zA-z0-9]{4}$/.test(value)) {
                callback(new Error('图片验证码有误，请重新输入'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        msgCode: [
          {required: true, message: '请输入短信验证码', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (!/^[a-zA-z0-9]{6}$/.test(value)) {
                callback(new Error('短信验证码有误，请重新输入'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (value.length < 6) {
                callback(new Error('密码应不少于6个字符'))
              } else if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,20}/.test(value)) {
                callback(new Error('密码必须由数字和字母组成'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ]
      },
      isAgreed: false, // 是否同意用户协议
      imgCodeSrc: this.$api + '/pc/sys/verify', // 图片验证码
      isImgCodeRight: false, // 图片验证码是否正确
      sendMsg: false, // 是否已发送短信验证码
      msgTip: '获取验证码', // 获取短信验证码提示语
      time: 0 // 重新获取验证码时间，单位: 秒
    }
  },
  mounted () {
    this.$store.commit('setHeaderTit', '注册')
  },
  methods: {
    // 获取图片验证码
    getImgCode () {
      let time = new Date()
      this.imgCodeSrc = this.$api + '/pc/sys/verify?time=' + Date.parse(time)
      this.isImgCodeRight = false
      if (this.$refs.signForm) {
        this.$refs.signForm.$children[1].resetField()
      }
    },
    // 检查图片验证码是否正确
    checkImgCode () {
      if (this.signForm.imgCode) {
        this.$http.post(this.$api + '/pc/sys/checkImgCode', {
          imgCode: this.signForm.imgCode
        }).then(res => {
          if (res.responseCode === '0000') {
            this.isImgCodeRight = true
          } else {
            this.isImgCodeRight = false
            this.$message.error({
              duration: this.$store.state.duration,
              message: res.responseMsg
            })
          }
        })
      } else {
        return false
      }
    },
    // 发送短信验证码
    sendMsgCode () {
      if (this.signForm.mobile && this.isImgCodeRight && /^1[3456789]\d{9}$/.test(this.signForm.mobile)) {
        this.$http.post(this.$api + '/pc/sys/sendMsg', {
          mobile: this.signForm.mobile,
          operateType: this.signForm.operateType
        }).then(res => {
          if (res.responseCode === '0000') {
            this.sendMsg = true
            this.$message({
              type: 'success',
              message: '验证码已发送，请注意查收'
            })
          } else {
            this.$message.error({
              duration: this.$store.state.duration,
              message: res.responseMsg
            })
          }
        })
      } else {
        this.$message.error('请输入正确的手机号码和图片验证码')
      }
    },
    // 注册
    signup () {
      this.$refs.signForm.validate(valid => {
        if (valid) {
          if (this.isAgreed) {
            this.$http.post(this.$api + '/pc/customer/regist', {
              mobile: this.signForm.mobile,
              password: Md5(this.signForm.password),
              imgCode: this.signForm.imgCode,
              msgCode: this.signForm.msgCode
            }).then(res => {
              if (res.responseCode === '0000') {
                this.$message({
                  type: 'success',
                  duration: this.$store.state.duration,
                  message: res.responseMsg,
                  onClose: () => {
                    this.$router.push('/login')
                  }
                })
              } else {
                this.$message.error({
                  duration: this.$store.state.duration,
                  message: res.responseMsg
                })
              }
            })
          } else {
            this.$message.info({
              message: '请先阅读并同意好茶仓的＜用户协议＞'
            })
          }
        } else {
          return false
        }
      })
    }
  },
  watch: {
    // 检测到已发送短信验证码禁用发送按钮并开始倒计时
    'sendMsg': function () {
      if (this.sendMsg) {
        this.time = 60
      } else {
        return false
      }
    },
    // 短信验证码倒计时
    'time': function () {
      if (this.sendMsg) {
        if (this.time === 0) {
          this.sendMsg = false
          this.msgTip = '获取验证码'
        } else {
          setTimeout(() => {
            this.time--
            this.msgTip = '重新发送(' + this.time + ')'
          }, 1000)
        }
      } else {
        this.msgTip = '获取验证码'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/scss/basic.scss';
.signup {
  position: absolute;
  top: 40px;
  left: 50%;
  margin-left: 200px;
  width: 400px;
  background: #fff;
  box-shadow: 0 8px 15px rgba(0, 0, 0, 0.3);
  .header {
    padding: 20px 10px 0 40px;
    height: 60px;
    background: $bg_color;
    border-bottom: solid 1px $border_color;
    .title {
      float: left;
      font-size: $fz_18;
      color: $f_main;
    }
    .link {
      float: right;
      font-size: $fz_14;
      color: $f_sub;
      &:hover {
        color: $red;
      }
    }
  }
  .body {
    padding: 30px 40px;
    .sign-btn {
      margin: 10px 0;
      width: 100%;
      height: 45px;
      line-height: 45px;
      font-size: $fz_16;
      text-align: center;
      letter-spacing: 0.5em;
      color: #ffffff;
      background: $green;
      cursor: pointer;
      transition: all 0.3s;
      &:hover {
        background: $green_l;
      }
    }
    .image-code {
      display: block;
      width: 99px;
      height: 34px;
      cursor: pointer;
    }
  }
}
</style>
